<template>
  <div>

    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary"
                     @click="isAddVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList"
                style="width: 100%"
                border
                stripe>
        <!-- 表头拓展 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
                    v-for="(item1, i1) in scope.row.children"
                    :key="item1.id">
              <!-- 一级标签 -->
              <el-col :span="5">
                <el-tag closable
                        @close="removeRight(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级标签 -->
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                        v-for="(item2, i2) in item1.children"
                        :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success"
                            closable
                            @close="removeRight(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级标签 -->
                  <el-col :span="18">
                    <el-tag :class="[i3 === 0 ? '' : 'bdtop']"
                            v-for="(item3, i3) in item2.children"
                            :key="item3.id"
                            type="warning"
                            closable
                            @close="removeRight(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"
                         label="ID"></el-table-column>
        <el-table-column prop="roleName"
                         label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc"
                         label="角色描述">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="primary"
                       icon="el-icon-edit"
                       @click="editDialog(scope.row.id)">编辑</el-button>
            <el-button size="mini"
                       type="danger"
                       icon="el-icon-delete"
                       @click="deleteRole(scope.row.id)">删除</el-button>
            <el-button size="mini"
                       type="warning"
                       icon="el-icon-setting"
                       @click="getRights(scope.row)">分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹出框 -->
    <el-dialog title="添加角色"
               :visible.sync="isAddVisible"
               width="50%">
      <el-form ref="addRolesFromRef"
               :model="addRolesFrom"
               :rules="addRolesFromRules"
               label-width="80px">
        <el-form-item label="角色名称"
                      prop="roleName">
          <el-input v-model="addRolesFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述"
                      prop="roleDesc">
          <el-input v-model="addRolesFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="isAddVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色弹出框 -->
    <el-dialog title="编辑角色"
               :visible.sync="isEditVisible"
               width="50%">
      <el-form ref="editRolesFromRef"
               :model="editRolesFrom"
               :rules="editRolesFromRules"
               label-width="80px">
        <el-form-item label="角色名称"
                      prop="roleName">
          <el-input v-model="editRolesFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述"
                      prop="roleDesc">
          <el-input v-model="editRolesFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="isEditVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色弹出框 -->
    <el-dialog title="分配角色"
               :visible.sync="isSetDialogVisible"
               width="50%"
               @close="setRightsDialogClose">
      <el-tree :data="rightsTree"
               :props="rightProps"
               show-checkbox
               node-key="id"
               default-expand-all
               :default-checked-keys="leafKeys"
               ref="rightsTreeRef"></el-tree>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="isSetDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.getRolesList()
  },
  data () {
    return {
      rolesList: [],
      isAddVisible: false,
      addRolesFrom: {
        roleName: '',
        roleDesc: ''
      },
      addRolesFromRules: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      isEditVisible: false,
      editRolesFrom: {},
      editRolesFromRules: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      isSetDialogVisible: false,
      rightsTree: {},
      rightProps: {
        children: 'children',
        label: 'authName'
      },
      leafKeys: [],
      roleId: ''
    }
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
    },
    addRoles () {
      this.$refs.addRolesFromRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.post('roles', this.addRolesFrom)
        if (res.meta.status !== 201) return this.$message.error('创建角色失败')
        this.getRolesList()
        this.isAddVisible = false
      })
    },
    async editDialog (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('加载失败')
      this.editRolesFrom = res.data
      this.isEditVisible = true
    },
    editRoles () {
      this.$refs.editRolesFromRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.put('roles/' + this.editRolesFrom.roleId, { roleName: this.editRolesFrom.roleName, roleDesc: this.editRolesFrom.roleDesc })
        if (res.meta.status !== 200) return this.$message.error('编辑失败')
        this.$message.success('编辑成功')
        this.getRolesList()
        this.isEditVisible = false
      })
    },
    async deleteRole (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if ('cancel' === confirmResult) return this.$message.info('已取消删除')

      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('用户删除失败')

      this.$message.success('删除成功')
      this.getRolesList()
    },
    async removeRight (role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if ('cancel' === confirmResult) return this.$message.info('已取消删除')

      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')

      this.$message.success('删除成功')

      //这里没有调用this.getRoleList方法来重新获取数据
      //这样直接赋值主要是为了防止删除后拓展栏自动关闭，提高用户体验
      role.children = res.data
    },
    async getRights (role) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限树失败')
      this.rightsTree = res.data
      this.roleId = role.id
      this.getLeafKeys(role, this.leafKeys)
      this.isSetDialogVisible = true
    },
    getLeafKeys (node, arr) {
      if (!node.children) return arr.push(node.id)

      node.children.forEach(item =>
        this.getLeafKeys(item, arr)
      )
    },
    setRightsDialogClose () {
      this.leafKeys = []
    },
    async setRights () {
      const keys = [
        ...this.$refs.rightsTreeRef.getCheckedKeys(),
        ...this.$refs.rightsTreeRef.getHalfCheckedKeys()
      ]
      const keysStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: keysStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.getRolesList()
      this.$message.success('分配权限成功')
      this.isSetDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
